package com.xxx.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.exception.MallException;
import com.xxx.mall.mapper.AttrCategoryMapper;
import com.xxx.mall.model.AttrCategory;
import com.xxx.mall.service.AttrCategoryService;
import com.xxx.mall.vo.CategoryVO;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性与分类关联信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-23
 */
@Service
public class AttrCategoryServiceImpl extends ServiceImpl<AttrCategoryMapper, AttrCategory> implements AttrCategoryService {

    @Override
    public void saveAttrCategory(Long attrId, List<Long> categoryIds) {
        if (CollUtil.isEmpty(categoryIds)) {
            throw new IllegalArgumentException("至少选择一种分类");
        }
        List<AttrCategory> categoryList = categoryIds.stream().map(id -> {
            AttrCategory attrCategory = new AttrCategory();
            attrCategory.setCategoryId(id);
            attrCategory.setAttrId(attrId);
            return attrCategory;
        }).collect(Collectors.toList());
        AttrCategoryService proxy = (AttrCategoryService) AopContext.currentProxy();
        proxy.saveBatch(categoryList);
    }

    @Override
    public void updateAttrCategory(Long attrId, List<Long> categoryIds) {
        if (CollUtil.isEmpty(categoryIds)) {
            throw new MallException("至少选择一种分类");
        }
        List<Long> dbIds = baseMapper.getCategoryIdsByAttrId(attrId);
        List<Long> addIds = new ArrayList<>(categoryIds.size());
        addIds.addAll(categoryIds);
        addIds.removeAll(dbIds);
        if (CollUtil.isNotEmpty(addIds)) {
            //保存
            baseMapper.insertBatch(attrId, addIds);
        }
        dbIds.removeAll(categoryIds);
        if (CollUtil.isNotEmpty(dbIds)) {
            //删除
            baseMapper.deleteBatch(attrId, dbIds);
        }
    }

    @Override
    public List<CategoryVO> ListByAttrId(Long id) {
        return baseMapper.ListByAttrId(id);
    }
}
